package com.sam.spring.security.compent;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @classname: CustomExpiredSessionStrategy
 * @description: 自定义处理策略类
 * @Author: sam
 * @date: 2021/7/4 10:01
 */
public class CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy{
    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();

    private ObjectMapper objectMapper=new ObjectMapper();

    /**
     * 当Session失效后的处理策略
     */
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 跳转到 指定页面。
        // redirectStrategy.sendRedirect(sessionInformationExpiredEvent.getRequest(),sessionInformationExpiredEvent.getResponse(),"/index");

        Map<String,Object> map = new HashMap<>();
        map.put("code",403);
        map.put("msg","您的登录已经超时或者已经在另一台机器登录，您被迫下线。"+ event.getSessionInformation().getLastRequest());
        String respMsp = objectMapper.writeValueAsString(map);
        event.getResponse().setContentType("application/json;charset=utf-8");
        event.getResponse().getWriter().write(respMsp);
    }
}
